import {observable, action, computed} from 'mobx'

/**
 * 增加页码时，如果新页码大于等于旧页码，关闭页面重新获取数据
 *
 * 页码变化时，开启页面重新获取数据
 *
 * 更新pagination时，开启页面重新获取数据
 */
class Pagination {
  @observable canUpDate: boolean = true

  @observable pagination = {
    page: 1,
    size: 20,
    total: 0,
    totalPage: 0
  }

  @action.bound
  updatePagination({
    page,
    size = 20,
    total,
    totalPage
  }: {
    page: number
    size?: number
    total: number
    totalPage: number
  }) {
    this.pagination.page = page
    this.pagination.size = size
    this.pagination.total = total
    this.pagination.totalPage = totalPage || Math.ceil(total / size)
  }

  @action.bound
  addPage(fn: (page: number, size: number) => void) {
    const page = this.pagination.page
    const totalPage = this.pagination.totalPage

    if (page >= totalPage) {
      this.closeUpdate()
      this.pagination.page = totalPage
    } else {
      this.pagination.page = page + 1
      this.openUpdate()
      fn && fn(this.pagination.page, this.pagination.size)
      console.log('%c历史记录继续加载', 'color:green')
      console.log('当前页码 和 总页码', this.pagination.page, totalPage)
    }
  }

  @action.bound
  delPage() {
    const page = this.pagination.page
    if (page <= 0) {
      this.closeUpdate()
      this.pagination.page = 1
    } else {
      this.openUpdate()
      this.pagination.page = page - 1
    }
  }

  @action.bound
  resetPagination() {
    this.openUpdate()
    this.pagination.page = 1
    this.pagination.size = 20
    this.pagination.totalPage = 0
  }

  @action.bound
  closeUpdate() {
    console.log('%c关闭分页加载', 'color:red')
    this.canUpDate = false
  }
  @action.bound
  openUpdate() {
    console.log('%c开启分页加载', 'color:green')
    this.canUpDate = true
  }
}

export default Pagination
